import {ModalForm, ProFormText, ProFormTextArea} from '@ant-design/pro-components';
import {Button, Form, message} from 'antd';
import React, {useState} from 'react';
import {createNamespace, updateNamespace} from '@/services/namespace/api';
import {useIntl, useRequest} from '@umijs/max';
import {FormattedMessage} from "@@/plugin-locale";

export type CreateFormProps = {
  isCreate: boolean;
  values?: API.NamespaceItem;
  reload?: () => void;
  trigger?: React.ReactNode;
  run?: (params: Partial<API.NamespaceItem>) => Promise<any>;
  loading?: boolean;
};

const CreateUpdateForm: React.FC<CreateFormProps> = (props) => {
  const {values, trigger, isCreate, run: runFromProps, loading: loadingFromProps} = props;
  const intl = useIntl();
  // 如果 trigger 不存在，则默认打开 Modal
  const [isModalOpen, setIsModalOpen] = useState(!trigger);
  const [form] = Form.useForm();

  const [messageApi, contextHolder] = message.useMessage();

  const {run: internalRun, loading: internalLoading} = useRequest(
    (params: Partial<API.NamespaceItem>) => {
      return isCreate ? createNamespace(params) : updateNamespace(params);
    },
    {
      manual: true,
      onSuccess: () => {
        console.log(isCreate ? '创建成功' : '更新成功')
        messageApi.success(isCreate ? '创建成功' : '更新成功');
        setIsModalOpen(false);
        props.reload && props.reload();
      },
      onError: () => {
        console.log(isCreate ? '创建失败，请重试' : '更新失败，请重试')
        messageApi.error(isCreate ? '创建失败，请重试' : '更新失败，请重试');
        setIsModalOpen(false);
      },
    },
  );

  const run = runFromProps || internalRun;
  const loading = loadingFromProps !== undefined ? loadingFromProps : internalLoading;

  const renderFormContent = (
    <>
      <ProFormText
        name="name"
        label="空间名称"
        formItemProps={{
          style: {
            marginTop: "15px",
          },
          labelCol: {
            style: {
              paddingBottom: "10px",
            }
          },
        }}
        fieldProps={{
          style: {
            width: "95%"
          },
        }}

        rules={[{required: true, message: '请输入空间名称'}]}
      />
      <ProFormText
        name="tag"
        label={
          <>
            空间标签
            <span style={{color: '#999', fontSize: '12px', marginLeft: '8px'}}>
                (创建后不可修改)
                </span>
          </>
        }
        formItemProps={{
          style: {
            marginTop: "20px"
          },
          labelCol: {
            style: {
              paddingBottom: "10px",
            }
          },
        }}
        fieldProps={{
          style: {
            width: "95%"
          },
          disabled: !isCreate
        }}
        rules={[{required: true, message: '请输入空间标签'}]}
      />
      <ProFormTextArea
        name="description"
        label="描述"
        formItemProps={{
          style: {
            marginTop: "20px",
            marginBottom: "60px"
          },
          labelCol: {
            style: {
              paddingBottom: "10px",
            }
          },
        }}
        fieldProps={{
          style: {
            width: "95%"
          }
        }}
        rules={[{required: true, message: '请介绍一下这个命名空间'}]}
      />
    </>
  );


  return (
    <>
      {contextHolder}
      {trigger ? (
        <>
          <span onClick={() => setIsModalOpen(true)}>{trigger}</span>
          <ModalForm
            form={form}
            width={640}
            style={{
              paddingTop: '10px',
              marginLeft: "20px"
            }}
            labelCol={{flex: "0 0 25%"}}
            wrapperCol={{flex: "0 0 75%"}}
            title={isCreate ? intl.formatMessage({
              id: 'pages.namespace.searchTable.create',
              defaultMessage: '新建命名空间',
            }) : intl.formatMessage({
              id: 'pages.namespace.searchTable.editChild',
              defaultMessage: '编辑命名空间',
            })}
            open={isModalOpen}
            onOpenChange={setIsModalOpen}
            initialValues={values}
            submitter={{
              searchConfig: {
                resetText: '重置',
                submitText: '提交',
              },
              submitButtonProps: {
                type: 'primary',
                style: {
                  marginLeft: "10px"
                },
                loading: loading,
              },
              resetButtonProps: {
                onClick: () => {
                  if (isCreate) {
                    form.resetFields();
                  } else {
                    form.setFieldsValue({name: undefined, description: undefined});
                  }
                },
              },
            }}
            modalProps={{
              styles: {
                header: {
                  paddingTop: '10px',
                  paddingLeft: '10px'
                },
              },
              destroyOnClose: true
            }}
            onFinish={async (formValues) => {
              const params = {...values, ...formValues};
              await run(params);
            }}
          >
            {renderFormContent}
          </ModalForm>
        </>
      ) : (
        <Form
          form={form}
          layout="vertical"
          size="large"
          onFinish={async (formValues) => {
            const params = {...values, ...formValues};
            await run(params);
          }}
          initialValues={values}
        >
          {renderFormContent}
          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading} block>
              <FormattedMessage id="pages.index.namespace.createGo" defaultMessage="创建并进入"/>
            </Button>
          </Form.Item>
        </Form>
      )}
    </>
  );
};

export default CreateUpdateForm;
